######################################
# target
######################################
TARGET = main

######################################
# building variables
######################################
# debug build?
DEBUG = 1
# optimization
OPT = --model-small

#######################################
# paths
#######################################
# Build path
BUILD_DIR = build

######################################
# source
######################################
# C sources
C_SOURCES = $(wildcard *.c)
# ASM sources
ASM_SOURCES =


#######################################
# binaries
#######################################
CC = sdcc
AS = sdas8051
CP = sdobjcopy
SZ = -size

HEX = packihx
BIN = sdobjcopy

#######################################
# CFLAGS
#######################################
# mcu
MCU = -mmcs51

# macros for gcc
# AS defines
AS_DEFS =

# C defines
C_DEFS =

# AS includes
AS_INCLUDES =

# C includes
C_INCLUDES = -I..

# compile gcc flags
ASFLAGS = $(MCU) $(AS_DEFS) $(AS_INCLUDES) $(OPT) -l -s

CFLAGS = $(MCU) $(C_DEFS) $(C_INCLUDES) $(OPT)

ifeq ($(DEBUG), 1)
CFLAGS +=
endif

#######################################
# LDFLAGS
#######################################
# libraries
LIBS =
LIBDIR =
LDFLAGS = $(MCU) --out-fmt-ihx $(LIBDIR) $(LIBS)

# default action: build all
all: $(BUILD_DIR)/$(TARGET).hex $(BUILD_DIR)/$(TARGET).bin
# $(BUILD_DIR)/$(TARGET).ihx 
#######################################
# build the application
#######################################
# list of objects
OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.rel)))
vpath %.c $(sort $(dir $(C_SOURCES)))
# list of ASM program objects
OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SOURCES:.s=.rel)))
vpath %.s $(sort $(dir $(ASM_SOURCES)))

$(BUILD_DIR)/%.rel: %.c Makefile | $(BUILD_DIR)
	$(CC) -o $@ -c $< $(CFLAGS)

$(BUILD_DIR)/%.rel: %.s Makefile | $(BUILD_DIR)
	$(AS) -o $@ -c $< $(CFLAGS)

$(BUILD_DIR)/$(TARGET).hex: $(OBJECTS) Makefile
	$(CC) -o $@ $(OBJECTS) $(LDFLAGS)
	$(SZ) $@

$(BUILD_DIR)/%.hex: $(BUILD_DIR)/%.ihx | $(BUILD_DIR)
	$(HEX) $< > $@

$(BUILD_DIR)/%.bin: $(BUILD_DIR)/%.hex | $(BUILD_DIR)
	$(BIN) -I ihex -O binary $< $@

$(BUILD_DIR):
	mkdir $@

#######################################
# clean up
#######################################
clean:
	-rm -fR $(BUILD_DIR)/*
	-rm -fR $(BUILD_DIR)

# *** EOF ***